package hoowin.app.wsnd.dao.springImp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import hoowin.app.wsnd.dao.IDiscussionDao;
import hoowin.app.wsnd.model.Discussion;
import hoowin.basic.util.Trans;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class DiscussionDao extends JdbcDaoSupport implements IDiscussionDao {

	@Override
	public Discussion getDiscussionById(int id) {
		String sql = "select * from apps_wsnd_discussions where id="+id;
		return (Discussion)super.getJdbcTemplate().queryForObject(sql, new DiscussionRowMapper());
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List getDiscussionListByStatusId(int statusId) {
		String sql = "select * from apps_wsnd_discussions where to_status="+statusId;
		return super.getJdbcTemplate().query(sql,new DiscussionRowMapper());
	}

	@Override
	public int addDiscussion(Discussion discussion) {
		String sql = "insert into apps_wsnd_discussions (id, to_user, to_status, publish_time, content, publisher) values (null, ?, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, discussion.getToUserId(), discussion.getStatusId(), Trans.dateToString(new Date()), discussion.getContent(), discussion.getPublisherId())>0){
			return super.getJdbcTemplate().queryForInt("select last_insert_id()");
		}else return 0;
	}

	@Override
	public boolean deleteDiscussionById(int id) {
		if(super.getJdbcTemplate().update("delete from apps_wsnd_discussions where id="+id)>0)return true;
		return false;
	}

	@Override
	public boolean deleteDiscussionsByStatusId(int statusId) {
		if(super.getJdbcTemplate().update("delete from apps_wsnd_discussions where to_status="+statusId)>0)return true;
		return false;
	}
	
	class DiscussionRowMapper implements RowMapper<Object>{

		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			Discussion discussion = new Discussion();
			discussion.setId(rs.getInt("id"));
			discussion.setPublisherId(rs.getInt("publisher"));
			discussion.setToUserId(rs.getInt("to_user"));
			discussion.setPublishTime(Trans.stringToDate(rs.getString("publish_time")));
			discussion.setStatusId(rs.getInt("to_status"));
			discussion.setContent(rs.getString("content"));
			return discussion;
		}
	}
}
